<template>
  <a-card title="角色管理" style="width: 100%">
    <a slot="extra" href="javascript:void(0)" @click="showModal('insert',{})">添加</a>
    <a-table :columns="columns"
             :loading="isloading"
             :pagination="false"
             :data-source="rolePage.data"
             rowKey="roleId">
      <!--      角色是否可用-->
      <span slot="available" slot-scope="available">
      <a-tag
          :color="available === 1 ? 'green':'red'"
      >
        {{ available === 1 ? '可用' : '不可用' }}
      </a-tag>
    </span>
      <!--      操作-->
      <span slot="action" slot-scope="text, record">
      <a-space>
        <a-button type="primary"
                  :disabled="record.roleId === 1 && $store.state.user.loginUser.type !== 1" @click="clickHandler('auth',record)" size="small" icon="lock" title="授权"></a-button>
        <a-button type="primary"
                  :disabled="record.roleId === 1 && $store.state.user.loginUser.type !== 1" @click="clickHandler('edit',record)" size="small" icon="edit" title="编辑"></a-button>
        <a-button type="danger"
                  size="small"
                  icon="delete"
                  title="删除"
                  @click="clickHandler('remove',record)"
                  :disabled="record.canDelete === 0"></a-button>
      </a-space>
    </span>

      <template slot="footer">
        <a-pagination
            style="text-align: end"
            :page-size-options="['2', '4', '5']"
            :total="rolePage.total"
            v-model="rolePage.pageNum"
            show-size-changer
            :page-size="rolePage.pageSize"
            @showSizeChange="onPageSizeChangeHandler"
            @change="onPageChangeHandler"
        >
          <template slot="buildOptionText" slot-scope="props">
            <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
            <span v-if="props.value === '50'">全部</span>
          </template>
        </a-pagination>
      </template>
    </a-table>
    <!--    编辑模态框-->
    <a-modal
        :title="ModalText"
        :visible="visible"
        :confirm-loading="confirmLoading"
        okText="确认"
        okType="primary"
        cancelText="放弃"
        @ok="handleOk"
        @cancel="handleCancel"
    >
      <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <a-form-item label="角色名">
          <a-input
              v-decorator="['roleName', {
                initialValue: currentRole.roleName,
                rules: [{ required: true, message: '请输入角色名!' }] }]"
          />
        </a-form-item>

        <a-form-item label="角色描述">
          <a-input
              v-decorator="['roleDesc', {
                initialValue: currentRole.roleDesc,
                rules: [{ required: true, message: '请输入角色描述!' }] }]"
          />
        </a-form-item>

        <a-form-item label="是否可用">
          <a-select
              v-decorator="[
              'available',{
                initialValue: currentRole.available,
                rules: [{ required: true, message: '选择是否可用!' }] },
        ]"
              placeholder="请选择是否可用"
          >
            <a-select-option :value="1">
              可用
            </a-select-option>
            <a-select-option :value="0">
              不可用
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
<!--    授权-->
    <a-modal
        title="授权"
        :visible="authVisible"
        :confirm-loading="authConfirmLoading"
        okText="确认"
        okType="primary"
        cancelText="放弃"
        @ok="authHandleOk"
        @cancel="authHandleCancel"
    >
      <a-tree
          v-model="hasMenuIds"
          checkable
          checkStrictly
          :expanded-keys="expandedKeys"
          :auto-expand-parent="autoExpandParent"
          :selected-keys="selectedKeys"
          :tree-data="menuTreeList"
          @expand="onExpand"
          @select="onSelect"
      />
    </a-modal>

  </a-card>
</template>

<script>
import {DEFAULT_PAGENUM, DEFAULT_PAGESIZE} from "@/constent";
import {getMenuIdsByRoleId, getRoleList, removeRole, saveMenuToRole, updateRole} from "@/api/role";
import {getMenuTreeList} from "@/api/menu";
const columns = [
  {
    title: '角色编号',
    dataIndex: 'roleId',
    key: 'roleId',
    align:'center',
    scopedSlots: { customRender: 'roleId' },
  },
  {
    title: '角色名',
    dataIndex: 'roleName',
    key: 'roleName',
    align:'center',
    scopedSlots: { customRender: 'roleName' },
  },
  {
    title: '角色描述',
    dataIndex: 'roleDesc',
    key: 'roleDesc',
    align:'center',
  },
  {
    title: '是否可用',
    key: 'available',
    align:'center',
    dataIndex: 'available',
    scopedSlots: { customRender: 'available' },
  },
  {
    title: '操作',
    key: 'action',
    align:'center',
    scopedSlots: { customRender: 'action' },
  },
];
export default {
  name: "RoleList",
  data(){
    return {
      ModalText:'',
      isloading: false,
      rolePage:{
        total:20,
        pageNum:DEFAULT_PAGENUM,
        pageSize:DEFAULT_PAGESIZE,
      },
      columns,
      queryParam:{
        pageSize:DEFAULT_PAGESIZE,
        pageNum:DEFAULT_PAGENUM
      },
      // 编辑模态框是否显示
      visible: false,
      // 确认加载中
      confirmLoading: false,
      // 编辑菜单
      currentRole:{},
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),

      // 授权
      menuTree: {},
      menuTreeList:[],
      hasMenuIds:[],
      authVisible: false,
      // 确认加载中
      authConfirmLoading: false,
      // 展开指定节点
      expandedKeys: ['1'],
      // 自动展开父节点
      autoExpandParent: true,
      selectedKeys: []
    }
  },
  mounted() {
    // 加载树形菜单
    this.getTreeMenuList();
  },
  watch:{
    // 监视参数变化
    queryParam:{
      immediate:true,
      deep:true,
      handler(){
        this.getMenus();
      }
    }
  },
  methods:{
    // 获得属性结构菜单
    async getTreeMenuList(){
      const {code,msg,data} = await getMenuTreeList();
      if (code === 200){
        this.menuTree = data;
        this.menuTreeList.push(data);
      }else{
        this.$message.error(msg);
      }
    },
    // 获取角色
    async getMenus(){
      this.isloading = true;
      const { pageNum,pageSize } = this.queryParam;
      const result = await getRoleList(pageNum,pageSize);
      const { code,data,msg } = result;
      if (code === 200){
        this.isloading = false;
        this.rolePage = data;
      } else {
        this.$message.error(msg);
      }
    },
    // 点击处理器
    clickHandler(opera,recode){
      if ('auth' === opera){
        this.showModal('auth',recode);
      } else if('edit' === opera){
        this.showModal('edit',recode);
      } else if('remove' === opera){
        this.remove(recode);
      }
    },
    // 删除角色
    remove(record){
      const _this = this;
      this.$confirm({
        title: '删除角色',
        content: '此操作将会删除该角色及用户对应的权限,请谨慎操作?',
        okText: '确认',
        okType: 'danger',
        cancelText: '放弃',
        onOk() {
          removeRole(record.roleId).then(res => {
            const { code,msg } = res;
            if (code === 200){
              _this.$message.success(msg);
              _this.getMenus();
              _this.$store.dispatch('getMenuList');
            } else {
              _this.$message.error(msg);
            }
          }).catch(error => {
            console.log(error);
            _this.$message.error("操作异常");
          })
        },
        onCancel() {
          console.log("取消了删除");
        },
      });
    },
    // 展示模态框
    async showModal(type,recode) {
      this.currentRole = recode;
      if ('edit' === type){
        this.ModalText = '编辑角色';
        this.visible = true;
      } else if ('insert' === type){
        this.ModalText = '添加角色';
        this.visible = true;
      } else if ('auth' === type){
        this.authVisible = true;
        const {code,data,msg} = await getMenuIdsByRoleId(recode.roleId);
        if (code === 200){
          this.hasMenuIds = data;
        }else {
          this.$message.error(msg);
        }
      }
    },
    // 点击了确定
    handleOk(e) {
      const _this = this;
      this.form.validateFields(async (err, values) => {
        if (!err) {
          _this.ModalText = '正在处理中...';
          _this.confirmLoading = true;
          let role = {...values,roleId:_this.currentRole.roleId};
          const result = await updateRole(role);
          const {code,msg} = result;
          if (code === 200){
            _this.$message.success(msg);
            _this.getMenus();
            _this.$store.dispatch('getMenuList');
          } else {
            _this.$message.error(msg);
          }
          setTimeout(() => {
            _this.visible = false;
            _this.confirmLoading = false;
            _this.currentRole = {};
            _this.form.resetFields();
          }, 1000);
        }
      });
    },
    // 点击了取消
    handleCancel(e) {
      console.log('Clicked cancel button');
      this.visible = false;
    },
    // 图标变化
    iconChange(e){
      this.currentRole.icon = e.target.value;
    },
    /**
     * 每页显示条数改变回调
     * @param current
     * @param pageSize
     */
    onPageSizeChangeHandler(current, pageSize) {
      this.queryParam.pageSize = pageSize;
      this.queryParam.pageNum = DEFAULT_PAGENUM;
    },

    /**
     * 当前页改变回调
     * @param current
     * @param pageSize
     */
    onPageChangeHandler(current){
      this.queryParam.pageNum = current;
    },

    // 授权
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onSelect(selectedKeys, info) {
      this.selectedKeys = selectedKeys;
    },

    // 确认授权
    async authHandleOk(){
      const roleId = this.currentRole.roleId;
      const roleObj = {
        roleId,
        ids: this.hasMenuIds.checked
      };
      this.authConfirmLoading = true;
      const {code,msg} = await saveMenuToRole(roleObj);
      if (code === 200){
        this.$message.success(msg);
        this.getMenus();
        this.$store.dispatch('getMenuList');
      }else {
        this.$message.error(msg);
      }
      setTimeout(() => {
        this.authVisible = false;
        this.authConfirmLoading = false;
        this.currentRole = {};
      }, 1000);
    },

    authHandleCancel(e) {
      console.log('Clicked cancel button');
      this.authVisible = false;
    },
  }
}
</script>

<style scoped>

</style>
